<template>
  <el-button type="primary" @click="dialogVisible=true">添加</el-button>

  <!--添加标签弹出框-->
  <el-dialog
      v-model="dialogVisible"
      :title="isAdd?'添加':'修改'"
      width="30%"
      :before-close="handleClose">
    <el-form ref="formRef"
             :model="categoryFrom"
             :rules="rules"
             label-width="80px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="categoryFrom.categoryName" type="text" maxlength="20"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="分类排序" prop="categoryRank">
        <el-input v-model.number="categoryFrom.categoryRank"/>
      </el-form-item>
      <!--  分类的图标  -->
      <el-form-item label="分类图标" prop="categoryIcon">
        <el-upload
            class="avatar-uploader"
            name="categoryIcon"
            :auto-upload="true"
            action="/api/category/uploadIcon"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="getUploadIconUrl" :src="getUploadIconUrl" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <!--  分类是否启用 -->
      <el-form-item label="标签状态" prop="isUse">
        禁用
        <el-switch v-model="categoryFrom.isUse"
                   style="margin:0px 5px;--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"/>
        启用
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="categoryOperation">
          保存
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>

  <el-divider direction="vertical"></el-divider>
  <el-input
      v-model="searchText"
      placeholder="搜索分类"
      size="default"
      style="width: 350px"
      clearable
      maxlength="12"
      show-word-limit
      @clear="getAll"
      @keydown.enter="getAll"
  >
    <template #append>
      <el-button @click="getAll">
        <el-icon>
          <Search/>
        </el-icon>
      </el-button>
    </template>
  </el-input>
  <el-divider direction="vertical"></el-divider>
  <el-button :icon="Refresh" :loading="loading" @click="refreshTable">
    <span>刷新</span>
  </el-button>
  <el-divider direction="vertical"></el-divider>
  <el-button :loading="loading" type="danger" :disabled="DeleteManyDisable" @click="deleteMany">
    <span>批量删除</span>
  </el-button>

  <el-divider></el-divider>
  <!--展示区域-->
  <el-table :data="tableData" @selection-change="handleSelectionChange" stripe style="width: 100%">
    <el-table-column type="selection" width="55"/>
    <el-table-column prop="categoryId" label="Id" width="80" sortable/>
    <el-table-column prop="categoryName" label="分类名称" min-width="220"/>
    <el-table-column prop="categoryIcon" label="图标" width="220">
      <template #default="scope">
        <el-popover :width="280" placement="right">
          <template #reference>
            <el-avatar shape="square" size="large" :src="scope.row.categoryIcon"
                       style="border: 1px solid #454555"/>
          </template>
          <img :src="scope.row.categoryIcon" style="width: 250px">
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="categoryRank" label="排序等级" width="150" sortable/>
    <el-table-column prop="blogCount" label="文章数量" width="150" sortable/>
    <el-table-column prop="isUse" label="启用状态" width="150">
      <template #default="scope">
        <el-switch v-model="scope.row.isUse" @change="updateCategory(scope.row)"
                   style="margin:0px 5px;--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"/>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-link type="danger" @click="deleteCategory(scope.row.categoryId)">
          <el-icon>
            <Delete/>
          </el-icon>
        </el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link type="primary" @click="editCategory(scope.row)">
          <el-icon>
            <Edit/>
          </el-icon>
        </el-link>
      </template>
    </el-table-column>
  </el-table>

  <el-divider></el-divider>
  <!--分页-->
  <div style="display: flex;">
    <el-pagination
        v-model:current-page="current"
        v-model:page-size="size"
        :page-sizes="[15, 30, 45, 60]"
        :small="true"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin: auto;"
    />
  </div>

</template>

<script>
import {Refresh, Search} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

export default {
  name: "CategoryManage",
  computed: {
    getUploadIconUrl() {
      if (this.uploadIconUrl) {
        return this.uploadIconUrl
      } else {
        return ""
      }
    },
  },
  data() {
    return {
      Refresh, Search,
      // 上传图片的url
      uploadIconUrl: "",
      loading: false,
      searchText: "",
      dialogVisible: false,
      // false 表示修改标签
      isAdd: true,
      categoryFrom: {
        categoryId: null,
        categoryName: "",
        categoryIcon: "",
        categoryRank: 1,
        isUse: true,
      },
      rules: {
        categoryName: [
          {required: true, message: '请输入分类', trigger: 'blur'},
          {min: 1, max: 20, message: '分类名称长度应该在1-20', trigger: 'blur'},
        ],
      },
      tableData: [],
      total: 0,
      current: 1,
      size: 15,
      DeleteManyDisable: true,
      multipleSelection: []
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    async getAll() {
      let {data: result} = await this.$http.get("/api/category/getCategories", {
        params: {
          pageSize: this.size,
          pageNum: this.current,
          searchText: this.searchText
        }
      })
      this.tableData = result.dataMap.page.records
      this.current = result.dataMap.page.current
      this.total = result.dataMap.page.total
      this.size = result.dataMap.page.size
    },
    refreshTable() {
      this.loading = true
      this.getAll()
      this.loading = false
    },
    handleClose() {
      this.$refs.formRef.resetFields()
      this.dialogVisible = false
      this.categoryFrom = {
        categoryId: null,
        categoryName: "",
        categoryIcon: "",
        categoryRank: 1,
        isUse: true,
      }
      this.uploadIconUrl = ""
      this.isAdd = true
    },
    categoryOperation() {
      if (this.isAdd) {
        this.addCategory()
      } else {
        this.updateCategory(this.categoryFrom)
      }
    },
    editCategory(item) {
      // es6 新特性，深拷贝
      this.categoryFrom = {...item}
      this.uploadIconUrl = item.categoryIcon
      this.isAdd = false
      this.dialogVisible = true
    },
    addCategory() {
      this.$refs.formRef.validate(async (validate) => {
        if (validate) {
          let {data: result} = await this.$http.post("/api/category/saveCategory", this.categoryFrom)
          if (result.code === 400) {
            ElMessage.error({
              showClose: true, message: result.msg
            })
          } else {
            ElMessage.success({
              showClose: true, message: result.msg
            })
            this.handleClose()
            this.refreshTable()
          }
        } else {
          ElMessage.error({
            showClose: true, message: "表单填写有误！"
          })
        }
      })
    },
    async updateCategory(item) {
      this.loading = true
      let {data: result} = await this.$http.post("/api/category/updateCategory", item)
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.loading = false
      this.handleClose()
      this.refreshTable()
    },

    async deleteCategory(categoryId) {
      this.loading = true
      let {data: result} = await this.$http.get("/api/category/deleteCategory", {
        params: {
          categoryId: categoryId,
        }
      })
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },
    async deleteMany() {
      this.loading = true
      let {data: result} = await this.$http.post("/api/category/deleteMany", this.multipleSelection.value)
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },
    // 上传前检查文件格式和大小
    beforeAvatarUpload(rawFile) {
      // console.log(rawFile.type)
      // console.log(typeof rawFile.type)
      // console.log(rawFile.type !== 'image/jpeg')
      let allowTypes = ['image/jpeg', "image/jpg", 'image/png', 'image/webp', 'image/icon'];
      if (!allowTypes.includes(rawFile.type)) {
        ElMessage.error('文件格式不正确!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能大于 2MB!')
        return false
      }
      return true
    },
    // 上传成功修改预览
    handleAvatarSuccess(response) {
      console.log(response)
      let {code, dataMap} = response
      this.uploadIconUrl = dataMap.iconPath
      this.categoryFrom.categoryIcon = dataMap.iconPath
    },
    // 多选状态改变
    handleSelectionChange(val) {
      if (val.length === 0) {
        // 批量删除不可用
        this.DeleteManyDisable = true
      } else {
        this.DeleteManyDisable = false
      }
      let list = []
      val.forEach((item) => {
        list.push(item.categoryId)
      })
      this.multipleSelection.value = list
    },
    // 分页大小改变
    handleSizeChange() {
      this.refreshTable()
    },
    // 分页页数改变
    handleCurrentChange() {
      this.refreshTable()
    },
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  /*margin-left: 30px;*/
  border-radius: 20px;
}

.avatar-uploader {
  border: 1px solid #8c939d;
  border-radius: 20px;
  margin-left: 30px;
  height: 150px;
  width: 150px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;
}


.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 60px;
  align-items: center;
  text-align: center;
}
</style>